<?php

namespace app\mqnote\model;

use think\Model;
use think\Validate;


class CategoryModel extends Model
{
    protected $pk = 'cate_id';
    protected $table = 'mqnote_category';

    /**
     * 获取所有分类 返回树形数据
     */
    public function GetAll()
    {
        $data = $this->select();
        $tree = node_merge($data);
        return $tree;
    }

    /**
     * 添加新的分类
     * @param $data POST数据
     */
    public function AddCategory($data)
    {
        $validate = new Validate([
            'cate_name' => 'require',
            'parent_id' => 'require|number',
        ], [
            'cate_name.require' => '未指定分类名称',
            'parent_id.require' => '未指定父级目录',
            'parent_id.require' => '无效的父级目录',
        ]);
        if (!$validate->check($data)) {
            return ['code' => 1, 'msg' => $validate->getError()];
        }
        $this->save(['cate_name' => $data['cate_name'], 'parent_id' => $data['parent_id']]);
        return ['code' => 0, 'msg' => '添加分类成功'];
    }

    /**
     * 删除分类
     * @param $cate_id 删除目录id
     */
    public function DelCategory($cate_id)
    {
        if (!$this->destroy($cate_id)) {
            return ['code' => 1, 'msg' => '删除分类失败'];
        }
        return ['code' => 0, 'msg' => '删除分类成功'];
    }

    /**
     * 获取某个目录的所有子目录
     * @param int $cate_id 目录id
     */
    public function GetChild($cate_id)
    {
        return $this->where('parent_id',$cate_id)->select();
    }
}
